import { http } from '@kit.NetworkKit'
import { Res } from '../entry/Res'

let request = http.createHttp()

export function get<T>(url:string, params?:Object):Promise<T>{
  return new Promise<T>((resole, reject) => {
    if (params) {
      url += '?' + Object.keys(params).map((k) => `${k}=${params[k]}`).join('&')
    }
    request.request(url,{
      method: http.RequestMethod.GET
    })
      .then((res) => {
        if (res.responseCode == 200) {
          let t:T = JSON.parse(res.result as string)
          resole(t)
        }else {
          reject(new Error(`网络错误：${res.responseCode}`))
        }
      })
      .catch(e => reject(e))
  })
}

export function get1<T>(url:string,data?:object):Promise<T>{
  return new Promise<T>((resolve,reject) => { //异步
    if (data) {
      // url += '?' + Object.keys(data).map((k) => `${k} = ${data[k]}`).join('&')
      url += '?'+ Object.keys(data).map((k) => `${k}=${data[k]}`).join('&')
    }
    request.request(url,{
      // method:http.RequestMethod.GET //默认就是get，可写可不写
    })
      .then((response) => {
        if (response.responseCode == 200) {
          let res:Res<T> = JSON.parse(response.result.toString()) //解析，解析成为你指定的格式
          if (res.code == 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.message))
          }
        } else {
          reject(new Error(`网络错误${response.responseCode}`))
        }
      })
      .catch((e:Error) => {
        reject(e)
      })
  })
}

export function post<T>(url:string,data:object):Promise<T>{
  return new Promise<T>((resolve,reject) => {
    request.request(url,{
      method:http.RequestMethod.POST, //方法，请求方式为POST
      header:{"Content-Type":"application/json"}, //内容格式，当前格式为json(xml,protobuf,msgpack)
      extraData:data, //上传的数据
      readTimeout:5000, //读取超时时间
      connectTimeout:5000, //连接超时时间
    })
      .then((response) => {
        if (response.responseCode == 200) {
          let res:Res<T> = JSON.parse(response.result.toString()) //解析，解析成为你指定的格式
          if (res.code == 200) {
            resolve(res.data)
          } else {
            reject(new Error(res.message))
          }
        } else {
          reject(new Error(`网络错误${response.responseCode}`))
        }
      })
      .catch((e:Error) => {
        reject(e)
      })
  })
}